//
//  SDBaseData+Cache.m
//  SKinDiary
//
//  Created by pcyang on 16/6/26.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "SDBaseData+Cache.h"
#import "SDBaseData.h"
#import "SDCacheManagement.h"

@implementation SDBaseData (Cache)


- (NSTimeInterval)cacheExpireTime
{
    return 1;
}

- (NSString*)identifier
{
    return [NSString stringWithFormat:@"com.tencent.skindiary.%@",NSStringFromClass(self.class)];
}

- (NSString*)cachePath
{
    if (self.identifier)
    {
       // NSString * identifier = [NSString stringWithFormat:@"%@.cmd%ld",self.identifier, (long)[self getJceCmd]];
        //return [[self.class rootCachePath]stringByAppendingPathComponent:identifier];
    }
    
    return nil;
}

- (void)saveToFile
{
    NSString* path = [self cachePath];
    
    if (path)
    {
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self];
        [data writeToFile:path atomically:YES];
    }
}


- (void)resetFromCacheObject:(SDBaseData*)model
{
    self.modelData = model.modelData;
    self.lastUpdateTime = model.lastUpdateTime;
 //   [self resetWithResponseObj:self.modelData];
}

- (void)readFromFileWithCompletion:(void (^)(void))completion
{
    __weak typeof(self)weakSelf = self;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        SDBaseData* tmpData = [NSKeyedUnarchiver unarchiveObjectWithFile:[self cachePath]];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            __strong typeof(self)strongSelf = weakSelf;
            
            [strongSelf resetFromCacheObject:tmpData];
            
            if(completion)completion();
        });
    });
}

-(BOOL)readFromFile
{
    NSString* path = [self cachePath];
    
    if(NO==[SDFile fileExist:path])
        return NO;
    
    SDBaseData* tmpData = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    [self resetFromCacheObject:tmpData];
    
    return YES;
}

+ (NSString*)rootCachePath
{
    NSString* rootCachePath = [NSString stringWithFormat:@"%@/%@/%@",[SDCacheManagement rootCachePath],@"datamodel",NSStringFromClass(self.class)];
    [SDFile checkDirectoryPath:rootCachePath];
    return rootCachePath;
    
}


-(BOOL)needCache
{
    return YES;
}

+ (void)cleanCache
{
    [SDFile deleteItem:[self rootCachePath]];
}

@end



